package fr.univ.lille1.android.adapters;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.annotations.RootContext;

import fr.univ.lille1.android.R;
import fr.univ.lille1.android.domain.Message;
import fr.univ.lille1.android.utils.Utils;

@EBean
public class CommentAdapter extends BaseAdapter {
	private final List<Message> mComments = new ArrayList<Message>();
	@RootContext
	Context mContext;

	@Override
	public int getCount() {
		return mComments.size();
	}

	@Override
	public Message getItem(int position) {
		return mComments.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Message item = getItem(position);
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.view_comment, parent, false);
			holder = new ViewHolder(mContext, convertView);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.bind(item.getContent(), item.getDate().getTime(), item.getUser()
				.getName());
		return convertView;
	}

	/**
	 * Add and replace all comments of the list.
	 * 
	 * @param comments
	 *            New comments of the list.
	 * @return boolean
	 */
	public boolean addAll(final List<Message> comments) {
		mComments.clear();
		return mComments.addAll(comments);
	}

	private static class ViewHolder {
		private final TextView mTextViewContent;
		private final TextView mTextViewDetails;
		private final Context mContext;

		public ViewHolder(Context context, View v) {
			mContext = context;
			mTextViewContent = (TextView) v.findViewById(R.id.textViewContent);
			mTextViewDetails = (TextView) v.findViewById(R.id.textViewDetails);
		}

		/**
		 * Bind data to the ui of the item comment view.
		 * 
		 * @param content
		 *            Content of the comment.
		 * @param timestamp
		 *            Date of the comment.
		 * @param author
		 *            Author of the comment.
		 */
		public void bind(final String content, final long timestamp,
				final String author) {
			final String patternDetail = mContext.getResources().getString(
					R.string.text_detail);
			final String patternDate = mContext.getResources().getString(
					R.string.pattern_date);
			final String date = Utils.convertLongToDate(timestamp, patternDate);
			final String details = String.format(patternDetail, date, author);
			mTextViewContent.setText(R.string.text_content);
			mTextViewDetails.setText(Html.fromHtml(details));
		}
	}

}